package com.flnet.spsys.utils;

import com.google.code.kaptcha.Constants;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * kaptcha 工具类
 *
 */
public class KaptchaUtil {

    /**
     * @param inputName input 提交的name值
     * @param suffix 传递验证码controller的suffix参数
     * @return 是否验证通过
     */
    public static Boolean validationKaptcha(final String inputName,final String suffix,final Boolean enable){
        if (enable){
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            String kaptchaValue = request.getParameter(inputName).trim();
            String sessionValue =(String)request.getSession().getAttribute(kaptchaKeyGenerator(suffix));
            return !(StringUtils.isEmpty(kaptchaValue) || !kaptchaValue.equalsIgnoreCase(sessionValue));
        }else {
            return true;
        }
    }

    /**
     * @param inputName input 提交的name值
     * @return 是否验证通过
     */
    public static Boolean validationKaptcha(final String inputName,final Boolean enable){
        return validationKaptcha(inputName,"",enable);
    }

    /**
     * @param kaptchaParamSuffix 验证码传递参数的后缀 验证码参数后缀
     * @return 返回生成的验证码 session key
     */
    public static String kaptchaKeyGenerator(final String kaptchaParamSuffix){
        if (StringUtils.isEmpty(kaptchaParamSuffix)){
            return Constants.KAPTCHA_SESSION_KEY;
        }else {
            return Constants.KAPTCHA_SESSION_KEY + "_"+ Base64Utils.encodeToUrlSafeString(kaptchaParamSuffix.getBytes());
        }
    }
}
